using System;
using System.Collections.Generic;
using System.Linq;
using PEMath;
using UnityEngine;

/****************************************************
// 功能：主要逻辑单位 技能处理
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/28 16:31:15
*****************************************************/

public partial class MainLogicUnit
{

    protected Skill[] skillArr;
    private List<LogicTimer> timerList;
    private List<Buff> buffList;
    
    /// <summary>
    /// 初始化技能
    /// </summary>
    public void InitSkill()
    {
        var len = unitData.unitConfig.skillArr.Length;
        skillArr = new Skill[len];
        for (var i = 0; i < len; i++)
        {
            skillArr[i] = new Skill(unitData.unitConfig.skillArr[i], this);
        }

        timerList = new List<LogicTimer>();
        buffList = new List<Buff>();

        // 被动buff
        var pasvBuffArr = unitData.unitConfig.pasvBuff;
        if (pasvBuffArr == null) return;
        {
            for (var i = pasvBuffArr.Length - 1; i >= 0; i--)
            {
                CreateSkillBuff(this, null, pasvBuffArr[i], null);
            }
        }

        OnDirChange += ClearFreeAniCallback;
    }
    
    /// <summary>
    /// 驱动技能
    /// </summary>
    public void TickSkill()
    {
        // Buff tick
        for(var i = buffList.Count - 1; i >= 0; --i) {
            if(buffList[i].unitState == SubUnitState.None) {
                buffList[i].LogicUnInit();
                buffList.RemoveAt(i);
            }
            else {
                buffList[i].LogicTick();
            }
        }

        // timer tick
        for(var i = timerList.Count - 1; i >= 0; --i) {
            var timer = timerList[i];
            if(timer.IsActive) {
                timer.TickTimer();
            }
            else {
                timerList.RemoveAt(i);
            }
        }
    }

    /// <summary>
    /// 反初始化技能
    /// </summary>
    public void UnitSkill()
    {
        
    }

    public void InputSkillKey(SkillKey key)
    {
        for(var i = skillArr.Length - 1; i >= 0; i--)
        {
            if (skillArr[i].skillId != key.skillId) continue;
            var x = PEInt.zero;
            var z = PEInt.zero;
            x.ScaledValue = key.x_value;
            z.ScaledValue = key.z_value;
            var skillArgs = new PEVector3(x, 0, z);
            skillArr[i].ReleaseSkill(skillArgs);
            return;
        }

        Debug.LogError($"SkillId：{key.skillId} not is exits");
    }
    
    public void CreateLogicTimer(Action cb, PEInt waitTime) {
        var timer = new LogicTimer(cb, waitTime);
        timerList.Add(timer);
    }


    public Buff CreateSkillBuff(MainLogicUnit source, Skill skill, int buffID, object[] args = null) {
        Buff buff = ResourceManager.Instance.CreateBuff(source, this, skill, buffID, args);
        buff.LogicInit();
        buffList.Add(buff);
        return null;
    }
    
    public Bullet CreateSkillBullet(MainLogicUnit source, MainLogicUnit target, Skill skill) {
        var bullet = ResourceManager.Instance.CreateBullet(source, target, skill);
        bullet.LogicInit();
        BattleController.Instance.AddBullet(bullet);
        return bullet;
    }

    #region API Function
    public Skill GetSkillById(int skillId) {
        foreach (var t in skillArr)
        {
            if(t.skillId == skillId) {
                return t;
            }
        }
        Debug.LogError($"SkillID:{skillId} is not exist");
        return null;
    }
    public Skill GetNormalSkill()
    {
        return skillArr?[0];
    }
    
    public Skill[] GetAllSkill() {
        return skillArr;
    }


    // 清空free动画回调函数
    public void ClearFreeAniCallback()
    {
        for (var i = skillArr.Length - 1; i >= 0; i--)
        {
            skillArr[i].FreeAniCallback = null;
        }
    }
    
    /// <summary>
    /// 是否禁止释放技能
    /// </summary>
    /// <returns></returns>
    public bool IsForbidReleaseSkill() {
        return IsSilenced() || IsStunned() || IsKnockup();
    }

    public bool IsSkillSpelling()
    {
        return skillArr.Any(t => t.skillState == SkillState.SpellStart);
    }

    /// <summary>
    /// 是否可以释放技能
    /// </summary>
    /// <param name="skillId"></param>
    /// <returns></returns>
    public bool CancelReleaseSkill(int skillId)
    {
        return !IsSilenced() && !IsStunned() && !IsKnockup() && !IsSkillSpelling() && IsSkillReady(skillId);
    }
    
    
    private bool IsSkillReady(int skillId) {
        for(var i = skillArr.Length - 1; i >= 0; i--) {
            
            if(skillArr[i].skillId == skillId) {
                return skillArr[i].skillState == SkillState.None;
            }
        }
        Debug.LogWarning("skill id config error.");
        return false;
    }
    
    public Buff GetBuffById(int buffId)
    {
        return buffList.FirstOrDefault(t => t.cfg.buffId == buffId);
    }

    #endregion
    
}
